<template>
  <div class="personal-main">
    <div class="personal-pay">
      <h3><i>借款人信息认证</i></h3>

      <!-- 步骤条优化：添加描述文字，增强视觉区分 -->
      <el-steps :active="active" style="margin: 30px 0" align-center>
        <el-step
            title="填写借款人信息"
            description="请准确填写个人信息，带*为必填项"
        ></el-step>
        <el-step
            title="提交平台审核"
            description="我们将在2小时内完成审核"
        ></el-step>
        <el-step
            title="等待认证结果"
            description="审核结果将通过短信通知您"
        ></el-step>
      </el-steps>

      <!-- 步骤0：填写信息 -->
      <div v-if="active === 0" class="user-borrower">
        <!-- 表单分组优化：添加卡片样式和分隔 -->
        <div class="form-section">
          <h6>个人基本信息 <span class="required-desc">（带*为必填项）</span></h6>
          <el-form
              label-width="120px"
              :model="borrower"
              :rules="baseInfoRules"
              ref="baseForm"
          >
            <el-form-item label="年龄*" prop="age">
              <el-col :span="5">
                <el-input
                    v-model="borrower.age"
                    placeholder="请输入年龄（18-65岁）"
                    type="number"
                />
              </el-col>
            </el-form-item>

            <el-form-item label="性别*" prop="sex">
              <el-select v-model="borrower.sex" placeholder="请选择性别">
                <el-option :value="1" label="男" />
                <el-option :value="0" label="女" />
              </el-select>
            </el-form-item>

            <el-form-item label="婚否*" prop="marry">
              <el-select v-model="borrower.marry" placeholder="请选择婚姻状态">
                <el-option :value="1" label="是" />
                <el-option :value="0" label="否" />
              </el-select>
            </el-form-item>

            <el-form-item label="学历*" prop="education">
              <el-select v-model="borrower.education" placeholder="请选择学历">
                <el-option
                    v-for="item in educationList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="行业*" prop="industry">
              <el-select v-model="borrower.industry" placeholder="请选择所在行业">
                <el-option
                    v-for="item in industryList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="月收入*" prop="income">
              <el-select v-model="borrower.income" placeholder="请选择月收入范围">
                <el-option
                    v-for="item in incomeList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="还款来源*" prop="returnSource">
              <el-select v-model="borrower.returnSource" placeholder="请选择还款来源">
                <el-option
                    v-for="item in returnSourceList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>

        <div class="form-section">
          <h6>联系人信息 <span class="required-desc">（带*为必填项）</span></h6>
          <el-form
              label-width="120px"
              :model="borrower"
              :rules="contactRules"
              ref="contactForm"
          >
            <el-form-item label="联系人姓名*" prop="contactsName">
              <el-col :span="5">
                <el-input
                    v-model="borrower.contactsName"
                    placeholder="请输入联系人姓名"
                />
              </el-col>
            </el-form-item>

            <el-form-item label="联系人手机*" prop="contactsMobile">
              <el-col :span="5">
                <el-input
                    v-model="borrower.contactsMobile"
                    placeholder="请输入联系人手机号"
                />
              </el-col>
            </el-form-item>

            <el-form-item label="联系人关系*" prop="contactsRelation">
              <el-select v-model="borrower.contactsRelation" placeholder="请选择关系">
                <el-option
                    v-for="item in contactsRelationList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>

        <div class="form-section">
          <h6>身份认证信息 <span class="required-desc">（必传，否则无法通过审核）</span></h6>
          <el-form label-width="120px">
            <el-form-item label="身份证人像面*">
              <el-upload
                  :on-success="(res, file) => handleUpload(res, file, 'idCard1')"
                  :on-remove="handleRemove"
                  :on-progress="handleUploadProgress"
                  :multiple="false"
                  :action="uploadUrl"
                  :data="{ module: 'idCard1' }"
                  :limit="1"
                  list-type="picture-card"
                  :file-list="getFilesByType('idCard1')"
              >
                <i class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip">
                  支持JPG/PNG格式，大小不超过5MB
                </div>
              </el-upload>
            </el-form-item>

            <el-form-item label="身份证国徽面*">
              <el-upload
                  :on-success="(res, file) => handleUpload(res, file, 'idCard2')"
                  :on-remove="handleRemove"
                  :on-progress="handleUploadProgress"
                  :multiple="false"
                  :action="uploadUrl"
                  :data="{ module: 'idCard2' }"
                  :limit="1"
                  list-type="picture-card"
                  :file-list="getFilesByType('idCard2')"
              >
                <i class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip">
                  支持JPG/PNG格式，大小不超过5MB
                </div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>

        <div class="form-section">
          <h6>其他信息 <span class="optional-desc">（选填，可提高审核通过率）</span></h6>
          <el-form label-width="120px">
            <el-form-item label="房产信息">
              <el-upload
                  :on-success="(res, file) => handleUpload(res, file, 'house')"
                  :on-remove="handleRemove"
                  :on-progress="handleUploadProgress"
                  :multiple="false"
                  :action="uploadUrl"
                  :data="{ module: 'house' }"
                  list-type="picture-card"
                  :file-list="getFilesByType('house')"
              >
                <i class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip">
                  房产证/购房合同照片，支持JPG/PNG格式
                </div>
              </el-upload>
            </el-form-item>

            <el-form-item label="车辆信息">
              <el-upload
                  :on-success="(res, file) => handleUpload(res, file, 'car')"
                  :on-remove="handleRemove"
                  :on-progress="handleUploadProgress"
                  :multiple="false"
                  :action="uploadUrl"
                  :data="{ module: 'car' }"
                  list-type="picture-card"
                  :file-list="getFilesByType('car')"
              >
                <i class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip">
                  行驶证/车辆登记证照片，支持JPG/PNG格式
                </div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>

        <el-form label-width="120px" class="submit-section">
          <el-form-item>
            <el-button
                type="primary"
                :disabled="submitBtnDisabled"
                :loading="isSubmitting"
                @click="handleSubmit"
            >
              提交
            </el-button>
            <el-button
                style="margin-left: 10px"
                @click="resetForm"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤1：审核中 -->
      <div v-if="active === 1" class="audit-status">
        <div class="status-container">
          <el-alert
              title="您的认证申请已成功提交，请耐心等待"
              type="warning"
              show-icon
              :closable="false"
          >
            审核时间：周一至周五 8:00-20:00（预计2小时内完成）
          </el-alert>

          <!-- 审核进度提示 -->
          <div class="audit-progress">
            <el-progress
                :percentage="auditPercentage"
                stroke-width="6"
                status="warning"
            ></el-progress>
            <p class="progress-text">当前审核进度：{{ auditPercentage }}%</p>
          </div>
        </div>
      </div>

      <!-- 步骤2：审核结果 -->
      <div v-if="active === 2" class="audit-result">
        <div class="status-container">
          <!-- 审核通过 -->
          <div v-if="borrowerStatus === 2">
            <el-alert
                title="恭喜，您的认证审批已通过！"
                type="success"
                show-icon
                :closable="false"
            />
            <div class="result-actions">
              <NuxtLink to="/user/apply">
                <el-button type="success">
                  立即借款
                </el-button>
              </NuxtLink>
            </div>
          </div>

          <!-- 审核未通过 -->
          <div v-if="borrowerStatus === -1">
            <el-alert
                title="您的认证审批未通过"
                type="error"
                show-icon
                :closable="false"
            >
              <p>原因：{{ rejectReason || '信息不完善或不符合要求，请重新提交' }}</p>
            </el-alert>
            <div class="result-actions">
              <el-button
                  type="primary"
                  @click="restartAuth"
              >
                重新认证
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    const BASE_API = process.env.BASE_API

    return {
      active: null, // 当前步骤
      borrowerStatus: null, // 认证状态：0未认证 -1未通过 1审核中 2通过
      submitBtnDisabled: false,
      isSubmitting: false, // 提交加载状态
      auditPercentage: 0, // 审核进度百分比
      rejectReason: '', // 未通过原因

      // 借款人信息
      borrower: {
        age: '',
        sex: null,
        marry: null,
        education: '',
        industry: '',
        income: '',
        returnSource: '',
        contactsName: '',
        contactsMobile: '',
        contactsRelation: '',
        borrowerAttachList: [], // 附件列表
      },

      // 下拉列表数据
      educationList: [],
      industryList: [],
      incomeList: [],
      returnSourceList: [],
      contactsRelationList: [],

      // 上传配置
      uploadUrl: `${BASE_API}/api/oss/file/upload`,

      // 表单验证规则
      baseInfoRules: {
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        marry: [
          { required: true, message: '请选择婚姻状态', trigger: 'change' }
        ],
        education: [
          { required: true, message: '请选择学历', trigger: 'change' }
        ],
        industry: [
          { required: true, message: '请选择行业', trigger: 'change' }
        ],
        income: [
          { required: true, message: '请选择月收入', trigger: 'change' }
        ],
        returnSource: [
          { required: true, message: '请选择还款来源', trigger: 'change' }
        ]
      },

      contactRules: {
        contactsName: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度在2-20个字符之间', trigger: 'blur' }
        ],
        contactsMobile: [
          { required: true, message: '请输入联系人手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
        ],
        contactsRelation: [
          { required: true, message: '请选择联系人关系', trigger: 'change' }
        ]
      }
    }
  },

  async created() {
    await this.initPageData()
    // 步骤1时启动审核进度模拟
    if (this.active === 1) {
      this.startAuditSimulation()
    }
  },

  methods: {
    // 初始化页面数据
    async initPageData() {
      try {
        const { data } = await this.$axios.$get('/api/core/borrower/auth/getBorrowerStatus')
        this.borrowerStatus = data.borrowerStatus
        this.rejectReason = data.rejectReason || '' // 获取未通过原因

        // 设置当前步骤
        if (this.borrowerStatus === 0) {
          this.active = 0
          await this.initSelectData() // 加载下拉列表
        } else if (this.borrowerStatus === 1) {
          this.active = 1
        } else {
          this.active = 2
        }
      } catch (err) {
        this.$message.error('页面初始化失败，请刷新重试')
        console.error('初始化失败：', err)
      }
    },

    // 加载下拉列表数据
    async initSelectData() {
      const dictTypes = [
        'education', 'industry', 'income', 'returnSource', 'relation'
      ]

      try {
        for (const type of dictTypes) {
          const { data } = await this.$axios.$get(`/api/core/dict/findByDictCode/${type}`)
          switch (type) {
            case 'education':
              this.educationList = data.dictList
              break
            case 'industry':
              this.industryList = data.dictList
              break
            case 'income':
              this.incomeList = data.dictList
              break
            case 'returnSource':
              this.returnSourceList = data.dictList
              break
            case 'relation':
              this.contactsRelationList = data.dictList
              break
          }
        }
      } catch (err) {
        this.$message.error('下拉数据加载失败')
        console.error('下拉数据错误：', err)
      }
    },

    // 处理文件上传
    handleUpload(response, file, type) {
      if (response.code === 0) {
        this.borrower.borrowerAttachList.push({
          imageName: file.name,
          imageUrl: response.data.url,
          imageType: type
        })
        this.$message.success('上传成功')
      } else {
        this.$message.error(`上传失败：${response.message}`)
      }
    },

    // 处理文件删除
    async handleRemove(file) {
      try {
        // 调用删除接口
        await this.$axios.$delete(`/api/oss/file/remove?url=${file.response.data.url}`)
        // 从列表中移除
        this.borrower.borrowerAttachList = this.borrower.borrowerAttachList.filter(
            item => item.imageUrl !== file.response.data.url
        )
        this.$message.success('文件已删除')
      } catch (err) {
        this.$message.error('删除失败，请重试')
        console.error('删除文件错误：', err)
      }
    },

    // 上传进度处理
    handleUploadProgress(event) {
      // 可在此处添加上传进度提示
      console.log('上传进度：', event.percent)
    },

    // 根据类型获取已上传文件（用于回显）
    getFilesByType(type) {
      return this.borrower.borrowerAttachList
          .filter(item => item.imageType === type)
          .map(item => ({
            name: item.imageName,
            url: item.imageUrl,
            response: { data: { url: item.imageUrl } } // 适配element的file结构
          }))
    },

    // 提交表单
    async handleSubmit() {
      // 验证必填文件
      const hasIdCard1 = this.borrower.borrowerAttachList.some(item => item.imageType === 'idCard1')
      const hasIdCard2 = this.borrower.borrowerAttachList.some(item => item.imageType === 'idCard2')

      if (!hasIdCard1 || !hasIdCard2) {
        this.$message.error('请上传身份证正反面照片，否则无法提交')
        return
      }

      // 表单验证
      const baseValid = await this.$refs.baseForm.validate()
      const contactValid = await this.$refs.contactForm.validate()

      if (!baseValid || !contactValid) return

      // 提交数据
      try {
        this.isSubmitting = true
        await this.$axios.$post('/api/core/borrower/auth/save', this.borrower)
        this.$message.success('提交成功，即将进入审核')
        this.active = 1
        this.startAuditSimulation() // 启动审核模拟
      } catch (err) {
        this.$message.error(`提交失败：${err.response?.data?.message || '系统错误'}`)
      } finally {
        this.isSubmitting = false
      }
    },

    // 重置表单
    resetForm() {
      this.$refs.baseForm.resetFields()
      this.$refs.contactForm.resetFields()
      this.borrower.borrowerAttachList = []
      // 删除已上传的文件
      this.borrower.borrowerAttachList.forEach(item => {
        this.$axios.$delete(`/api/oss/file/remove?url=${item.imageUrl}`)
      })
      this.$message.success('表单已重置')
    },

    // 重新认证
    restartAuth() {
      this.active = 0
      this.borrowerStatus = 0
      this.borrower = { borrowerAttachList: [] } // 清空表单
      this.initSelectData() // 重新加载下拉数据
    },

    // 模拟审核进度（实际项目可替换为轮询接口）
    startAuditSimulation() {
      let percentage = 0
      const timer = setInterval(() => {
        percentage += Math.floor(Math.random() * 5) + 1
        if (percentage >= 100) {
          percentage = 100
          clearInterval(timer)
          // 模拟审核完成后跳转（实际应通过接口轮询结果）
          setTimeout(() => {
            this.initPageData() // 重新获取状态
          }, 1000)
        }
        this.auditPercentage = percentage
      }, 3000)
    }
  }
}
</script>

<style scoped>
.personal-pay {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.personal-pay h3 {
  font-size: 18px;
  color: #333;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.personal-pay h3 i {
  font-style: normal;
  color: #1890ff;
}

/* 表单分组样式 */
.form-section {
  margin-bottom: 30px;
  padding: 15px;
  background: #fafafa;
  border-radius: 6px;
}

.form-section h6 {
  font-size: 14px;
  color: #333;
  margin-bottom: 20px;
  padding-left: 5px;
  border-left: 3px solid #1890ff;
}

.required-desc {
  font-size: 12px;
  color: #f56c6c;
  margin-left: 10px;
}

.optional-desc {
  font-size: 12px;
  color: #67c23a;
  margin-left: 10px;
}

/* 提交区域 */
.submit-section {
  margin-top: 20px;
  text-align: center;
}

/* 审核状态样式 */
.audit-status, .audit-result {
  margin-top: 40px;
}

.status-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 30px;
  background: #fafafa;
  border-radius: 8px;
}

.audit-progress {
  margin-top: 30px;
  padding: 0 20px;
}

.progress-text {
  text-align: center;
  margin-top: 10px;
  color: #666;
}

/* 结果页样式 */
.result-actions {
  margin-top: 30px;
  text-align: center;
}

/* 步骤条样式优化 */
.el-steps {
  margin-bottom: 40px !important;
}

.el-step__description {
  color: #666 !important;
  margin-top: 5px !important;
}
</style>